package com.songcha.library_common.util

import android.app.Activity
import android.content.Context
import android.graphics.Paint
import android.graphics.Paint.FontMetrics
import android.graphics.Rect
import android.util.DisplayMetrics
import androidx.core.app.ActivityCompat.recreate
import com.songcha.library_common.LibraryCommon

class FontUtil {
    companion object{
        /***
         * can not measure ascent and descent
         */
        @JvmStatic
         fun getTextBounds(text:String,textPaint:Paint?=null,textSize:Float = 0f,isBold:Boolean = false): Rect?{
            if(text.isNullOrEmpty()) return null
            if(textPaint!=null){
                val bounds = Rect()
                textPaint.getTextBounds(text,0,text.length,bounds)
                return bounds
            }else{
                val newTextPaint= Paint(Paint.ANTI_ALIAS_FLAG)
                newTextPaint.textSize = textSize
                newTextPaint.isFakeBoldText=isBold
                val bounds=Rect()
                newTextPaint.getTextBounds(text,0,text.length,bounds)
                return bounds
            }

        }

        @JvmStatic
        fun measureText(text:String,textPaint:Paint?=null,textSize:Float = 0f,isBold:Boolean = false):Float{
            if(text.isNullOrEmpty()) return 0f
            if(textPaint!=null){
                return textPaint.measureText(text)
            }else{
                val newTextPaint= Paint(Paint.ANTI_ALIAS_FLAG)
                newTextPaint.textSize = textSize
                newTextPaint.isFakeBoldText = isBold
                return newTextPaint.measureText(text)
            }
        }

        @JvmStatic
        fun breakText(text:String,maxWidth:Float,textPaint:Paint):Int{
            if(text.isNullOrEmpty()) return 0
            var idx = 1
            while(idx <= text.length - 1 && textPaint.measureText(text.substring(0,idx)) < maxWidth){
                idx++
            }
            return idx
        }

        @JvmStatic
        fun getFontMetrics(textPaint:Paint?=null,textSize:Float = 0f,isBold:Boolean = false): Paint.FontMetrics{
            //if(text.isNullOrEmpty()) return null
            if(textPaint != null){
                return textPaint.fontMetrics
            }else{
                val newTextPaint = Paint(Paint.ANTI_ALIAS_FLAG)
                newTextPaint.textSize=textSize
                newTextPaint.isFakeBoldText=isBold
                return newTextPaint.fontMetrics
            }
        }

        @JvmStatic
        fun getCenterToBaseLine(fm:FontMetrics):Float{
            return (fm.bottom - fm.top) / 2 - fm.bottom
        }


    }
}